'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { signIn, signUp } from '@/lib/auth-client';
import LoadingSpinner from '@/components/ui/LoadingSpinner';
import { Eye, EyeOff } from 'lucide-react';

export default function AuthForm() {
  const router = useRouter();
  const [isLogin, setIsLogin] = useState(true); // true=登录模式, false=注册模式
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      if (isLogin) {
        // 登录
        const result = await signIn.email({
          email,
          password,
        });
        
        if (result.error) {
          setError(result.error.message || '登录失败，请检查您的邮箱和密码');
          return;
        }
        
        // 登录成功后跳转到examples页面
        router.push('/examples');
      } else {
        // 注册
        const result = await signUp.email({
          email,
          password,
          name,
        });
        
        if (result.error) {
          setError(result.error.message || '注册失败，请检查您的信息');
          return;
        }
        
        // 注册成功后也跳转到examples页面
        router.push('/examples');
      }
    } catch (error: any) {
      console.error('认证失败:', error);
      setError(error.message || '认证失败，请检查您的信息');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-md mx-auto mt-8 p-6 bg-white rounded-lg shadow-md">
      <h2 className="text-2xl font-bold mb-6 text-center">
        {isLogin ? '登录' : '注册'}
      </h2>
      
      {/* 错误提示 */}
      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md">
          <p className="text-red-700 text-sm">{error}</p>
        </div>
      )}
      
      <form onSubmit={handleSubmit} className="space-y-4">
        {/* 注册模式下显示姓名输入框 */}
        {!isLogin && (
          <div>
            <label className="block text-sm font-medium text-gray-700">
              姓名
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required={!isLogin}
            />
          </div>
        )}
        
        {/* 邮箱输入框 */}
        <div>
          <label className="block text-sm font-medium text-gray-700">
            邮箱
          </label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          />
        </div>
        
        {/* 密码输入框 */}
        <div>
          <label className="block text-sm font-medium text-gray-700">
            密码
          </label>
          <div className="mt-1 relative">
            <input
              type={showPassword ? "text" : "password"}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="block w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
              minLength={6}
            />
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-500 hover:text-gray-700"
            >
              {showPassword ? (
                <EyeOff className="h-4 w-4" />
              ) : (
                <Eye className="h-4 w-4" />
              )}
            </button>
          </div>
          {!isLogin && (
            <p className="mt-1 text-xs text-gray-500">
              密码至少需要6个字符
            </p>
          )}
        </div>
        
        {/* 提交按钮 */}
        <button
          type="submit"
          disabled={loading}
          className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center"
        >
          {loading ? (
            <LoadingSpinner size="sm" text="" className="text-white" />
          ) : (
            isLogin ? '登录' : '注册'
          )}
        </button>
      </form>
      
      {/* 切换登录/注册模式 */}
      <p className="mt-4 text-center text-sm text-gray-600">
        {isLogin ? '没有账户？' : '已有账户？'}
        <button
          onClick={() => setIsLogin(!isLogin)}
          className="ml-1 text-blue-600 hover:text-blue-500 underline"
        >
          {isLogin ? '注册' : '登录'}
        </button>
      </p>
    </div>
  );
}